package com.wkbb.sports.service.impl;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wkbb.common.base.BaseServiceImpl;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.sports.dto.*;
import com.wkbb.sports.enums.SportsModelTypeEnum;
import com.wkbb.sports.exception.MyException;
import com.wkbb.sports.exception.ResultEnum;
import com.wkbb.sports.mapper.HlifeWorkMapper;
import com.wkbb.sports.mapper.HlifeWorkStudentHistoryMapper;
import com.wkbb.sports.mapper.HlifeWorkStudentMapper;
import com.wkbb.sports.model.HlifeWork;
import com.wkbb.sports.model.HlifeWorkStudent;
import com.wkbb.sports.service.PcWorkService;
import com.wkbb.sports.utils.WeekUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author lbh
 * @date 2021年03月29日 17:58:34
 * @description: PC端作业实现类
 */
@Service
@Slf4j
public class PcWorkServiceImpl extends BaseServiceImpl<HlifeWork> implements PcWorkService {

    @Autowired
    private HlifeWorkMapper workMapper;

    @Autowired
    private HlifeWorkStudentMapper hlifeWorkStudentMapper;

    @Autowired
    private HlifeWorkStudentHistoryMapper hlifeWorkStudentHistoryMapper;

    //public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    public static SimpleDateFormat sdfMonth = new SimpleDateFormat("yyyy-MM");
    public static SimpleDateFormat sdfDate = new SimpleDateFormat("dd");

    //1、统计
    @Override
    public ResultDTO getPcIndex(String teacherId,String orgId,String classId){
        if(StringUtils.isEmpty(teacherId)){
            throw new MyException(ResultEnum.TEACHER_ID_IS_NULL);
        }

        if(StringUtils.isEmpty(orgId)){
            throw new MyException(ResultEnum.ORG_ID_IS_NULL);
        }

        Map<String,Object> teacherWorkMap=workMapper.getTeacherWorkForPcPercent(teacherId,orgId,classId);

        List<Map<String,Object>> resultMapList= Lists.newArrayList();
        Map<String,Object> resultMap1=Maps.newHashMap();
        Map<String,Object> resultMap2=Maps.newHashMap();
        Map<String,Object> resultMap3=Maps.newHashMap();
        Map<String,Object> resultMap4=Maps.newHashMap();
        Map<String,Object> resultMap5=Maps.newHashMap();
        resultMap1.put("name","累计作业数(个)");
        resultMap1.put("value",String.valueOf(teacherWorkMap.get("total")));

        resultMap2.put("name","未开始作业数(个)");
        resultMap2.put("value",String.valueOf(teacherWorkMap.get("unstart")));

        resultMap3.put("name","进行中作业数(个)");
        resultMap3.put("value",String.valueOf(teacherWorkMap.get("progress")));

        resultMap4.put("name","累计完成作业数(个)");
        resultMap4.put("value",String.valueOf(teacherWorkMap.get("finish")));

        resultMap5.put("name","进行中完成率");
        resultMap5.put("value",String.valueOf(teacherWorkMap.get("percent")));

        resultMapList.add(resultMap1);
        resultMapList.add(resultMap2);
        resultMapList.add(resultMap3);
        resultMapList.add(resultMap4);
        resultMapList.add(resultMap5);
        return new ResultDTO<>(resultMapList);
    }

    //2、本年级平均成绩结构对比
    @Override
    public ResultDTO getPcIndex2(String gradeName,String orgId,String time){
        if(StringUtils.isEmpty(gradeName)){
            throw new MyException(ResultEnum.GRADE_NAME_IS_NULL);
        }

        if(StringUtils.isEmpty(orgId)){
            throw new MyException(ResultEnum.ORG_ID_IS_NULL);
        }

        if(StringUtils.isNotEmpty(time)){
            if (!verifyDate(time)) {
                throw new MyException(ResultEnum.DATE_FORMAT_IS_ERROR);
            }
        }

        String [] gradeArray=new String[]{"一年级","二年级","三年级","四年级","五年级","六年级","初一","初二","初三","高一","高二","高三"};
        List<String> gradeList=Arrays.asList(gradeArray);
        gradeName=gradeName.trim();
        if(!gradeList.contains(gradeName)){
            throw new MyException(ResultEnum.GRADE_NAME_IS_ILLEGAL);
        }
        //String gradeName1=getNewGradeName(gradeName);
        String gradeName1=getNewGradeName1(gradeName);

        if(StringUtils.isEmpty(time) || sdfMonth.format(new Date()).equals(time) || sdfMonth.format(new Date()).compareTo(time)<0){
            //time=sdf.format(new Date());//2021-05-18    time为空或者time传过来的就是当前系统时间年月，那么截止时间就是当前日期往前倒推到1号
            time=sdfMonth.format(new Date());//2021-05    time为空或者time传过来的就是当前系统时间年月，那么截止时间就是当前日期往前倒推到1号
        }
        Map<String,Object> teacherWorkMap=workMapper.getPcIndex2(gradeName,gradeName1,orgId,time);
        Map<String,Object> teacherWorkMap1=workMapper.getPcIndex22(gradeName,gradeName1,orgId,time);

        String unReachedPercent="0";//未达标率
        String reachedPercent="0";//达标率
        String className="";//班级名称

        String unReachedCount="0";//未达标人数
        String reachedCount="0";//达标人数
        String unReachedPercentStr="0%";//未达标百分比率
        String reachedPercentStr="0%";//达标百分比率

        if(!CollectionUtils.isEmpty(teacherWorkMap)){
            unReachedPercent=String.valueOf(teacherWorkMap.get("unReachedPercent"));//98,8
            reachedPercent=String.valueOf(teacherWorkMap.get("reachedPercent"));//2,92
            className=String.valueOf(teacherWorkMap.get("className"));//六年级（1）班,六年级（2）班
        }

        if(!CollectionUtils.isEmpty(teacherWorkMap1)){
            unReachedCount=String.valueOf(teacherWorkMap1.get("unReachedCount"));//3269
            reachedCount=String.valueOf(teacherWorkMap1.get("reachedCount"));//71
            unReachedPercentStr=String.valueOf(teacherWorkMap1.get("unReachedPercentStr"));//98%
            reachedPercentStr=String.valueOf(teacherWorkMap1.get("reachedPercentStr"));//2%
        }

        return new ResultDTO<>(getTotalDate1(unReachedPercent,reachedPercent,className,unReachedCount,reachedCount,unReachedPercentStr,reachedPercentStr));
    }

    //图表1【柱形图】：
    //x轴：["六年级（1）班","六年级（2）班"]
    //指标：[
    //	{ name: '达标率', color: '#0FDD8D',  percent: '30%' ,num:'45'},
    //	{ name: '未达标率', color: '#7AEEEE',  percent: '60%',num:'33' }
    //]

    //data：[
    //  {
    //    name: '达标率',
    //    type: 'bar',
    //    stack: '成绩',
    //    barWidth: 18,
    //    data: [2, 92]
    //  },
    //  {
    //    name: '未达标率',
    //    type: 'bar',
    //    stack: '成绩',
    //    barWidth: 18,
    //    data: [98, 8]
    //  }
    //]

    public static Map<String,Object>  getTotalDate1(String unReachedPercent,String reachedPercent,String className,String unReachedCount,String reachedCount,String unReachedPercentStr,String reachedPercentStr){
        Map<String,Object> resultMap=Maps.newHashMap();

        List<String> unReachedPercentList= Lists.newArrayList();
        List<String> reachedPercentList= Lists.newArrayList();
        List<String> classNameList= Lists.newArrayList();
        if(StringUtils.isNotEmpty(unReachedPercent)){
            unReachedPercentList= Arrays.asList(unReachedPercent.split(","));
        }
        if(StringUtils.isNotEmpty(reachedPercent)){
            reachedPercentList= Arrays.asList(reachedPercent.split(","));
        }
        if(StringUtils.isNotEmpty(className)){
            classNameList= Arrays.asList(className.split(","));
        }

        List<DimensionDto> dimensionDtoList=Lists.newArrayList();
        List<DataDto> dataList=Lists.newArrayList();

        resultMap.put("xz",classNameList);//x轴为班级，格式为：["六年级（1）班","六年级（2）班"]

        DimensionDto dimensionDto1=new DimensionDto();
        dimensionDto1.setName("已达标");
        dimensionDto1.setColor("#0FDD8D");
        dimensionDto1.setNum(reachedCount);
        dimensionDto1.setPercent(reachedPercentStr);

        DimensionDto dimensionDto2=new DimensionDto();
        dimensionDto2.setName("未达标");
        dimensionDto2.setColor("#7AEEEE");
        dimensionDto2.setNum(unReachedCount);
        dimensionDto2.setPercent(unReachedPercentStr);

        dimensionDtoList.add(dimensionDto1);
        dimensionDtoList.add(dimensionDto2);

        DataDto dataDto1=new DataDto();
        dataDto1.setName("达标率");
        dataDto1.setType("bar");
        dataDto1.setStack("成绩");
        dataDto1.setBarWidth(18);
        dataDto1.setData(reachedPercentList);

        DataDto dataDto2=new DataDto();
        dataDto2.setName("未达标率");
        dataDto2.setType("bar");
        dataDto2.setStack("成绩");
        dataDto2.setBarWidth(18);
        dataDto2.setData(unReachedPercentList);

        dataList.add(dataDto1);
        dataList.add(dataDto2);
        resultMap.put("dataList",dataList);
        resultMap.put("dimensionDtoList",dimensionDtoList);
        //log.info("=======JSON.toJSONString(dateStringList)==========:"+ JSON.toJSONString(dateStringList));
        //log.info("=======JSON.toJSONString(percentNewList)==========:"+ JSON.toJSONString(percentNewList));
        //log.info("=======JSON.toJSONString(resultMap)==========:"+ JSON.toJSONString(resultMap));
        return resultMap;
    }

    public String getNewGradeName(String gradeName){
        String gradeName1="";
        switch (gradeName){
            case "七年级":
                gradeName1="初一";
                break;
            case "八年级":
                gradeName1="初二";
                break;
            case "九年级":
                gradeName1="初三";
                break;
            case "十年级":
                gradeName1="高一";
                break;
            case "十一年级":
                gradeName1="高二";
                break;
            case "十二年级":
                gradeName1="高三";
                break;
            default:
                gradeName1=gradeName;
                break;
        }

        return gradeName1;
    }

    public String getNewGradeName1(String gradeName){
        String gradeName1="";
        switch (gradeName){
            case "初一":
                gradeName1="七年级";
                break;
            case "初二":
                gradeName1="八年级";
                break;
            case "初三":
                gradeName1="九年级";
                break;
            case "高一":
                gradeName1="十年级";
                break;
            case "高二":
                gradeName1="十一年级";
                break;
            case "高三":
                gradeName1="十二年级";
                break;
            default:
                gradeName1=gradeName;
                break;
        }

        return gradeName1;
    }


    //3、我的作业布置统计
    @Override
    public ResultDTO getPcIndex3(String teacherId,String orgId,String time, Integer classId){
        if(StringUtils.isEmpty(teacherId)){
            throw new MyException(ResultEnum.TEACHER_ID_IS_NULL);
        }

        if(StringUtils.isEmpty(orgId)){
            throw new MyException(ResultEnum.ORG_ID_IS_NULL);
        }

        if(StringUtils.isNotEmpty(time)){
            if (!verifyDate(time)) {
                throw new MyException(ResultEnum.DATE_FORMAT_IS_ERROR);
            }
        }

        if(StringUtils.isEmpty(time) || sdfMonth.format(new Date()).equals(time) || sdfMonth.format(new Date()).compareTo(time)<0){
            //time=sdf.format(new Date());//2021-05-18    time为空或者time传过来的就是当前系统时间年月，那么截止时间就是当前日期往前倒推到1号
            time=sdfMonth.format(new Date());//2021-05    time为空或者time传过来的就是当前系统时间年月，那么截止时间就是当前日期往前倒推到1号
        }
        Map<String,Object> teacherWorkMap=workMapper.getPcIndex3(teacherId,orgId,classId,time);

        String total="";
        String createTime="";
        if(!CollectionUtils.isEmpty(teacherWorkMap)){
            total=String.valueOf(teacherWorkMap.get("total"));//5,1
            createTime=String.valueOf(teacherWorkMap.get("createTime"));//06,10
        }

        return new ResultDTO<>(getTotalDate(total,createTime,time,"作业布置统计"));
    }

    //4、学生作业提交率
    @Override
    public ResultDTO getPcIndex4(String teacherId,String orgId,String time, Integer classId){
        if(StringUtils.isEmpty(teacherId)){
            throw new MyException(ResultEnum.TEACHER_ID_IS_NULL);
        }

        if(StringUtils.isEmpty(orgId)){
            throw new MyException(ResultEnum.ORG_ID_IS_NULL);
        }

        if(StringUtils.isNotEmpty(time)){
            if (!verifyDate(time)) {
                throw new MyException(ResultEnum.DATE_FORMAT_IS_ERROR);
            }
        }

        if(classId == null){
            throw new MyException(ResultEnum.CLASS_ID_IS_NULL);
        }

        if(StringUtils.isEmpty(time) || sdfMonth.format(new Date()).equals(time) || sdfMonth.format(new Date()).compareTo(time)<0){
            //time=sdf.format(new Date());//2021-05-18    time为空或者time传过来的就是当前系统时间年月，那么截止时间就是当前日期往前倒推到1号
            time=sdfMonth.format(new Date());//2021-05    time为空或者time传过来的就是当前系统时间年月，那么截止时间就是当前日期往前倒推到1号
        }
        Map<String,Object> teacherWorkMap=workMapper.getPcIndex4(teacherId,orgId,classId,time);

        String percent="";
        String createTime="";
        if(!CollectionUtils.isEmpty(teacherWorkMap)){
            percent=String.valueOf(teacherWorkMap.get("percent"));//5,1
            createTime=String.valueOf(teacherWorkMap.get("createTime"));//06,10
        }

        return new ResultDTO<>(getTotalDate(percent,createTime,time,"学生作业达标率"));
    }

    //图表3【折线图】：
    //x轴：['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
    //data: [120, 132, 101, 134, 90, 230, 210, 132, 101, 134, 90, 230]
    public static Map<String,Object>  getTotalDate(String percent,String createTime,String time,String name){
        Map<String,Object> resultMap=Maps.newHashMap();
        //percent:1.9,0.0    createTime：06,10

        List<String> percentList= Arrays.asList(percent.split(","));
        List<String> createTimeList= Arrays.asList(createTime.split(","));

        //String time=sdf.format(new Date());//2021-05-18

        int date=0;
        if(StringUtils.isEmpty(time) || sdfMonth.format(new Date()).equals(time) || sdfMonth.format(new Date()).compareTo(time)<0){
            date=Integer.parseInt(sdfDate.format(new Date()));//18    time为空或者time传过来的就是当前系统时间年月，那么截止时间就是当前日期往前倒推到1号
        }else{ //指定时间小于当前系统时间月份
            Map<Integer,Object> map= WeekUtil.getWeek(time,"1"); //返回指定的某年某个月最后一天，即总天数，例如：31
            date=Integer.parseInt(String.valueOf(map.get(1)));
        }

        List<DataDto> dataList=Lists.newArrayList();
        List<String> dateStringList=Lists.newArrayList();
        List<String> percentNewList=Lists.newArrayList();
        for(int i=1;i<=date;i++){
            String d="";
            if(i<10){
                d="0"+i;
            }else{
               d=String.valueOf(i);
            }

            dateStringList.add(d);
            int index=createTimeList.indexOf(d);
            if(index>=0){
                percentNewList.add(percentList.get(index));
            }else{
                percentNewList.add("0");//不存在的时间段默认填充0
            }
        }

        resultMap.put("xz",dateStringList);//x轴为日期，格式为两位数天

        DataDto dataDto=new DataDto();
        //dataDto.setName("学生作业达标率");
        dataDto.setName(name);
        dataDto.setType("line");
        dataDto.setStack("总量");
        dataDto.setBarWidth(18);
        dataDto.setData(percentNewList);
        dataList.add(dataDto);
        resultMap.put("data",dataList);
        //resultMap.put("data",percentNewList);
        //resultMap.put("data",dataDto);
        //log.info("=======JSON.toJSONString(dateStringList)==========:"+ JSON.toJSONString(dateStringList));
        //log.info("=======JSON.toJSONString(percentNewList)==========:"+ JSON.toJSONString(percentNewList));
        //log.info("=======JSON.toJSONString(resultMap)==========:"+ JSON.toJSONString(resultMap));
        return resultMap;
    }

    public static void main(String[] args) {
        //System.out.println(sdfDate.format(new Date()));

        //getTotalDate("1.9,0.3,19","06,10,16","2021-04","作业布置统计");

        System.out.println(verifyDate("2021-05-01"));
    }


    /**
     * 判断时间格式 格式必须为“YYYY-MM-dd”
     * 2004-2-30 是无效的
     * 2003-2-29 是无效的
     * @param sDate
     * @return
     */
    private static boolean verifyDate(String sDate) {
        if ((sDate == null) || (sDate.length() !=7)) {
            return false;
        }

        try {
            Date date = sdfMonth.parse(sDate);
            return sDate.equals(sdfMonth.format(date));
        } catch (Exception e) {
            return false;
        }
    }

    /*public boolean verifyDate(String time){
        try {
            sdfMonth.parse(time);
//            System.out.println("=========日期解析成功==============");
            return true;
        }catch (ParseException e){
//            System.out.println("=========日期解析失败=============");
        }
        return false;
    }*/

    /**
     *  作业下拉选择列表
     * @param teacherId
     * @return
     */
    @Override
    public ResultDTO<List<Map<String,Object>>> getWorksByTeacherIdForPc(Integer teacherId,Integer orgId,Integer classId,String time){
        if(orgId == null){
            throw new MyException(ResultEnum.ORG_ID_IS_NULL);
        }

        if(teacherId == null){
            throw new MyException(ResultEnum.TEACHER_ID_IS_NULL);
        }

        if(classId == null){
            throw new MyException(ResultEnum.CLASS_ID_IS_NULL);
        }

        if(StringUtils.isNotEmpty(time)){
            if (!verifyDate(time)) {
                throw new MyException(ResultEnum.DATE_FORMAT_IS_ERROR);
            }
        }

        if(StringUtils.isEmpty(time) || sdfMonth.format(new Date()).equals(time) || sdfMonth.format(new Date()).compareTo(time)<0){
            //time=sdf.format(new Date());//2021-05-18    time为空或者time传过来的就是当前系统时间年月，那么截止时间就是当前日期往前倒推到1号
            //time=sdfMonth.format(new Date());//2021-05    time为空或者time传过来的就是当前系统时间年月，那么截止时间就是当前日期往前倒推到1号
        }

        Map params=Maps.newHashMap();
        params.put("teacherId",teacherId);
        params.put("orgId",orgId);
        params.put("classId",classId);
        params.put("time",time);
        List<Map<String,Object>> hifeWorkDtoList=workMapper.getWorksByTeacherIdForPc(params);
        return new ResultDTO<>(hifeWorkDtoList);
    }

    /**
     *  首页作业列表
     * @param workId
     * @return
     */
    @Override
    public ResultDTO<PageInfo<HlifeWorkStudent>> getIndexWorksByTeacherIdForPc(Integer workId, String time,int pageNo, int pageSize){
        if(workId == null){
            throw new MyException(ResultEnum.WORK_ID_IS_NULL);
        }

        if(StringUtils.isNotEmpty(time)){
            if (!verifyDate(time)) {
                throw new MyException(ResultEnum.DATE_FORMAT_IS_ERROR);
            }
        }

        if(StringUtils.isEmpty(time) || sdfMonth.format(new Date()).equals(time) || sdfMonth.format(new Date()).compareTo(time)<0){
            //time=sdf.format(new Date());//2021-05-18    time为空或者time传过来的就是当前系统时间年月，那么截止时间就是当前日期往前倒推到1号
            //time=sdfMonth.format(new Date());//2021-05    time为空或者time传过来的就是当前系统时间年月，那么截止时间就是当前日期往前倒推到1号
        }

        Map params=Maps.newHashMap();
        params.put("workId",workId);
        params.put("time",time);
        //List<HlifeWorkStudent> hifeWorkDtoList=workMapper.getIndexWorksByTeacherIdForPc(params);
        //return new ResultDTO<>(hifeWorkDtoList);

        Page<HlifeWorkStudent> page = PageHelper.startPage(pageNo, pageSize);
        params.put("no",(pageNo-1)*pageSize);
        List<HlifeWorkStudent> hifeWorkDtoList=workMapper.getIndexWorksByTeacherIdForPc(params);
        PageInfo<HlifeWorkStudent> pageInfo = new PageInfo<HlifeWorkStudent>(hifeWorkDtoList);
        pageInfo.setTotal(page.getTotal());
        return new ResultDTO<>(pageInfo);
    }

    /**
     *  最近作业列表
     * @param teacherId
     * @param classId
     * @return
     */
    @Override
    public ResultDTO getWorkListByTeacherIdForPc(Integer teacherId,Integer status,Integer type,Integer classId,Integer orgId,int pageNo,int pageSize,String flag,HttpServletResponse response) {
        if(orgId == null){
            throw new MyException(ResultEnum.ORG_ID_IS_NULL);
        }

        if(teacherId == null){
            throw new MyException(ResultEnum.TEACHER_ID_IS_NULL);
        }

        if(status != null){
            if(!(status ==0  ||status == 1 ||status == 2 ||status == 3)){
                throw new MyException(ResultEnum.STATUS_IS_ILLEGAL);
            }
        }

        if(type != null){
            if(!(type.equals(SportsModelTypeEnum.MOCKS.getValue()) || type.equals(SportsModelTypeEnum.LIMIT.getValue()) || type.equals(SportsModelTypeEnum.COUNT.getValue()) || type.equals(SportsModelTypeEnum.TIME.getValue()))){
                throw new MyException(ResultEnum.MODEL_TYPE_IS_ILLEGAL);
            }
        }

        Map params=Maps.newHashMap();
        params.put("teacherId",teacherId);
        params.put("classId",classId);
        params.put("orgId",orgId);
        params.put("status",status);
        params.put("type",type);
        /*if(StringUtils.isNotEmpty(achivement)){
            if(achivement.indexOf("-")>0){
                params.put("minAchivement",achivement.split("-")[0]);
                params.put("maxAchivement",achivement.split("-")[1]);
            }else{
                params.put("achivement",achivement);
            }
        }*/
        Page<ExcelDto1> page =null;
        if(StringUtils.equals(flag,"0")){
            page=PageHelper.startPage(pageNo, pageSize);
        }

        //List<Map<String,Object>> hifeWorkDtoList=workMapper.getWorkListByTeacherIdForPc(params);
        List<ExcelDto1> hifeWorkDtoList=workMapper.getWorkListByTeacherIdForPc(params);
        if(StringUtils.equals(flag,"0")){
            PageInfo<ExcelDto1> pageInfo = new PageInfo<ExcelDto1>(hifeWorkDtoList);
            pageInfo.setTotal(page.getTotal());
            return new ResultDTO<>(pageInfo);
        }

        List<ExcelDto11> hifeWorkDtoList1=Lists.newArrayList();
        hifeWorkDtoList.forEach(excelDto1->{
            ExcelDto11 excelDto11=new ExcelDto11();
            excelDto11.setNo(excelDto1.getNo());
            excelDto11.setGradeName(excelDto1.getGradeName());
            excelDto11.setClassName(excelDto1.getClassName());
            excelDto11.setTeacherName(excelDto1.getTeacherName());
            Integer type1=Integer.valueOf(excelDto1.getType());
            Integer status1=excelDto1.getStatus();
            if(type1.equals(SportsModelTypeEnum.MOCKS.getValue())){  //作业类型(1模拟考试 2限时限数3数量模式4时间模式)
                excelDto11.setType("模拟考试");
            }else if(type1.equals(SportsModelTypeEnum.LIMIT.getValue())){
                excelDto11.setType("限时限数");
            }else if(type1.equals(SportsModelTypeEnum.COUNT.getValue())){
                excelDto11.setType("数量模式");
            }else if(type1.equals(SportsModelTypeEnum.TIME.getValue())){
                excelDto11.setType("时间模式");
            }

            if(status1.equals(0)){  //状态(0未开始 1进行中 2已结束 3已取消)
                excelDto11.setStatus("未开始");
            }else if(status1.equals(1)){
                excelDto11.setStatus("进行中");
            }else if(status1.equals(2)){
                excelDto11.setStatus("已结束");
            }else if(status1.equals(3)){
                excelDto11.setStatus("已取消");
            }

            excelDto11.setCreateTime(excelDto1.getCreateTime());
            excelDto11.setPercent(excelDto1.getPercent());
            excelDto11.setDuration(excelDto1.getDuration());
            hifeWorkDtoList1.add(excelDto11);
        });
        return exportExcel(response,"作业列表",ExcelDto11.class,hifeWorkDtoList1);
        //return ExcelUtils.exportExcel(response,"作业列表",ExcelDto11.class,hifeWorkDtoList1);
        //return ExcelUtils.exportExcel(response,"作业列表",ExcelDto11,hifeWorkDtoList1);
        //return exportExcel(response,"作业列表",ExcelDto1.class,hifeWorkDtoList);
    }

    /**
     * 作业详情及统计
     * @param workId
     * @return
     */
    @Override
    public ResultDTO<Map<String,Object>> getWorkDetailForPc(Long workId){
        if(workId == null){
            throw new MyException(ResultEnum.WORK_ID_IS_NULL);
        }
        //作业信息详情
        Map<String,Object>  workDetailMap=workMapper.getWorkDetailForPc(workId);
        return new ResultDTO<>(workDetailMap);
    }

    /**
     * 作业学生详情
     * @param workId
     * @return
     */
    @Override
    public ResultDTO getWorkDetailStudentForPc(String workId,String studentNo,String studentName,String reached,Integer status,Integer sex,int pageNo,int pageSize,String flag,HttpServletResponse response){
        if(StringUtils.isEmpty(workId)){
            throw new MyException(ResultEnum.WORK_ID_IS_NULL);
        }

        if(StringUtils.isNotEmpty(reached)){
            if(!(StringUtils.equals(reached,"0") || StringUtils.equals(reached,"1") )){
                throw new MyException(ResultEnum.REACHED_IS_ILLEGAL);
            }
        }

        if(status != null){
            if(!(status ==0  ||status == 1 ||status == 2 ||status == 3)){
                throw new MyException(ResultEnum.STATUS_IS_ILLEGAL);
            }
        }

        if(sex != null){
            if(!(sex == 1 ||sex == 2)){
                throw new MyException(ResultEnum.SEX1_IS_ILLEGAL);
            }
        }
        Page<ExcelDto2> page =null;
        if(StringUtils.equals(flag,"0")) {
            page = PageHelper.startPage(pageNo, pageSize);
        }
        //List<HlifeWorkStudent> reachedList=hlifeWorkStudentMapper.getWorkDetailStudentForPc(workId,reached,studentNo,studentName,status,sex);
        List<ExcelDto2> reachedList=hlifeWorkStudentMapper.getWorkDetailStudentForPc(workId,reached,studentNo,studentName,status,sex);
        //List<Map<String,Object>> reachedList=hlifeWorkStudentMapper.getWorkDetailStudentForPc(workId,reached,studentNo,studentName,status,sex);
        if(StringUtils.equals(flag,"0")) {
            PageInfo<ExcelDto2> pageInfo = new PageInfo<ExcelDto2>(reachedList);
            //PageInfo<Map<String,Object>> pageInfo = new PageInfo<Map<String,Object>>(reachedList);
            pageInfo.setTotal(page.getTotal());
            return new ResultDTO<>(pageInfo);
        }

        List<ExcelDto22> reachedList1=Lists.newArrayList();
        reachedList.forEach(excelDto2->{
            ExcelDto22 excelDto22=new ExcelDto22();
            excelDto22.setNo(excelDto2.getNo());
            excelDto22.setUserNo(excelDto2.getUserNo());
            excelDto22.setStudentName(excelDto2.getStudentName());
            Integer status1=excelDto2.getStatus();
            Integer sex1=excelDto2.getSex();
            Integer reached1=excelDto2.getReached();
            if(sex1.equals(1)){  //性别(1男/2女)
                excelDto22.setSex("男");
            }else if(sex1.equals(2)){
                excelDto22.setSex("女");
            }

            if(status1.equals(0)){  //状态(0未开始 1进行中 2已结束 3已取消)
                excelDto22.setStatus("未开始");
            }else if(status1.equals(1)){
                excelDto22.setStatus("进行中");
            }else if(status1.equals(2)){
                excelDto22.setStatus("已结束");
            }else if(status1.equals(3)){
                excelDto22.setStatus("已取消");
            }

            if(reached1.equals(0)){  //是否达标(0未达标/1已达标)
                excelDto22.setReached("未达标");
            }else if(reached1.equals(1)){
                excelDto22.setReached("已达标");
            }
            excelDto22.setAchivement(excelDto2.getAchivement());
            excelDto22.setSpeed(excelDto2.getSpeed());
            reachedList1.add(excelDto22);
        });
        return exportExcel(response,"作业学生列表",ExcelDto22.class,reachedList1);
        //return exportExcel(response,"作业学生列表",ExcelDto2.class,reachedList);
    }

    /**
     * 个人作业记录【时长模式】
     * @param workId
     * @param studentId
     * @return
     */
    @Override
    public ResultDTO<Map<String,Object>> getStudentPersonalInfoDetailForPc(String workId,String studentId,String studentHistoryId,String orgId,String teacherName,String achivement, int pageNo, int pageSize,String flag,HttpServletResponse response){
        /*if(StringUtils.isEmpty(workId)){
            throw new MyException(ResultEnum.WORK_ID_IS_NULL);
        }*/
        /*if(StringUtils.isEmpty(studentHistoryId)){
            throw new MyException(ResultEnum.WORK_STUDENT_ID_IS_NULL);
        }*/
        if(StringUtils.isEmpty(studentId)){
            throw new MyException(ResultEnum.STUDENT_ID_IS_NULL);
        }

        Map<String,Object> finalMap=Maps.newHashMap();
        //学生个人信息
        Map<String,Object>  sudentPersonalInfoMap=workMapper.getStudentPersonalInfoDetailForPc1(studentId,orgId);
        if(!CollectionUtils.isEmpty(sudentPersonalInfoMap)) {
            String year = String.valueOf(sudentPersonalInfoMap.get("year"));
            Integer month = Integer.parseInt(String.valueOf(sudentPersonalInfoMap.get("month")));

            if (month > 2 && month < 8) {
                sudentPersonalInfoMap.put("term", year + " 第2学期");
            } else {
                sudentPersonalInfoMap.put("term", year + " 第1学期");
            }
            sudentPersonalInfoMap.remove("year");
            sudentPersonalInfoMap.remove("month");
        }
        finalMap.put("sudentPersonalInfoMap",sudentPersonalInfoMap);

        //================圆环图(个人成绩占比)======begin===============

        //模式(1模拟考试 2限时限数3数量模式4时间模式)
        //1模拟考试个人成绩占比
        //Map<String,Object>  percentMap1=workMapper.getStudentPersonalInfoDetailForPcPercent(studentId,orgId,"1");
        //2限时限数个人成绩占比
        //Map<String,Object>  percentMap2=workMapper.getStudentPersonalInfoDetailForPcPercent(studentId,orgId,"2");
        //3数量模式个人成绩占比
        //Map<String,Object>  percentMap3=workMapper.getStudentPersonalInfoDetailForPcPercent(studentId,orgId,"3");
        //4时间模式个人成绩占比
        Map<String,Object>  percentMap4=workMapper.getStudentPersonalInfoDetailForPcPercent(studentId,orgId,"4");

        List<Map<String, Object>> resultList=Lists.newArrayList();
        //getDimensionDto("模拟考试个人成绩占比",percentMap1,resultList);
        //getDimensionDto("限时限数个人成绩占比",percentMap2,resultList);
        //getDimensionDto("数量模式个人成绩占比",percentMap3,resultList);
        getDimensionDto("时间模式个人成绩占比",percentMap4,resultList);

        finalMap.put("percentMap",resultList);
        //================圆环图(个人成绩占比)=======end==============

        String minAchivement="";
        String maxAchivement="";
         if(StringUtils.isNotEmpty(achivement)){
            if(achivement.indexOf("-")>0){
                minAchivement=achivement.split("-")[0];
                maxAchivement=achivement.split("-")[1];
                achivement=null;
            }
        }

        //List<WorkStudentHistoryDto> workStudentHistoryList=hlifeWorkStudentHistoryMapper.getListByWorkStudentIdForPc(Integer.parseInt(studentHistoryId),orgId);
        //List<Map<String,Object>> workStudentHistoryList=hlifeWorkStudentHistoryMapper.getListByWorkStudentIdForPc(Integer.parseInt(studentHistoryId),orgId);
        //List<Map<String,Object>> workStudentHistoryList=hlifeWorkStudentHistoryMapper.getListByWorkStudentIdForPc1(Integer.parseInt(studentId),orgId,achivement,minAchivement,maxAchivement,teacherName);
        //finalMap.put("workStudentHistoryMap",workStudentHistoryList);
        //return new ResultDTO<>(finalMap);
        Page<ExcelDto3> page =null;
        if(StringUtils.equals(flag,"0")) {
            page = PageHelper.startPage(pageNo, pageSize);
        }
        List<ExcelDto3> workStudentHistoryList=hlifeWorkStudentHistoryMapper.getListByWorkStudentIdForPc1(Long.parseLong(studentId),Long.parseLong(orgId),achivement,minAchivement,maxAchivement,teacherName);
        if(StringUtils.equals(flag,"0")) {
            PageInfo<ExcelDto3> pageInfo = new PageInfo<ExcelDto3>(workStudentHistoryList);
            pageInfo.setTotal(page.getTotal());

            finalMap.put("workStudentHistoryMap", pageInfo);
            return new ResultDTO<>(finalMap);
        }

        workStudentHistoryList.forEach(excelDto3->{
            Integer type1=Integer.parseInt(excelDto3.getModelType());
            if(type1.equals(SportsModelTypeEnum.MOCKS.getValue())){  //作业类型(1模拟考试 2限时限数3数量模式4时间模式)
                excelDto3.setModelType("模拟考试");
            }else if(type1.equals(SportsModelTypeEnum.LIMIT.getValue())){
                excelDto3.setModelType("限时限数");
            }else if(type1.equals(SportsModelTypeEnum.COUNT.getValue())){
                excelDto3.setModelType("数量模式");
            }else if(type1.equals(SportsModelTypeEnum.TIME.getValue())){
                excelDto3.setModelType("时间模式");
            }
        });

        return exportExcel(response,"个人作业列表",ExcelDto3.class,workStudentHistoryList);
    }

    /*图表1(圆环图)：
           文字描述数据：
               [
                       {id: 1, name: '已达标', color: '#FFD02E', percent: '33.3%' },
                       {id: 2, name: '未达标', color: '#62F0FB', percent: 66.7%' }
               ]
                           图表渲染数据：
               [
                           {id: 1, value: 100, name: '已达标' },
                           {id: 2, value: 200, name: '未达标' }
               ]
               注：id作为上面两个数据的关联字段*/
    public List<Map<String, Object>> getDimensionDto(String modelName,Map<String,Object>  percentMap,List<Map<String, Object>> resultList){
        Map<String, Object> resultMap=Maps.newHashMap();
        List<DimensionDto> list=Lists.newArrayList();
        List<DimensionDto> list1=Lists.newArrayList();
        String unReached="0"; //未达标人数
        String reached="0";//已达标人数
        String unReachedPercent="0%";//未达标率
        String reachedPercent="0%";//已达标率
        if(!CollectionUtils.isEmpty(percentMap)){
            unReached=String.valueOf(percentMap.get("unReached"));
            reached=String.valueOf(percentMap.get("reached"));
            unReachedPercent=String.valueOf(percentMap.get("unReachedPercent"));
            reachedPercent=String.valueOf(percentMap.get("reachedPercent"));
        }

        DimensionDto dimensionDto=new DimensionDto();
        dimensionDto.setId("1");
        dimensionDto.setName("已达标");
        dimensionDto.setColor("#FFD02E");
        dimensionDto.setPercent(reachedPercent);

        DimensionDto dimensionDto1=new DimensionDto();
        dimensionDto1.setId("2");
        dimensionDto1.setName("未达标");
        dimensionDto1.setColor("#62F0FB");
        dimensionDto1.setPercent(unReachedPercent);
        list.add(dimensionDto);
        list.add(dimensionDto1);

        DimensionDto dimensionDto3=new DimensionDto();
        dimensionDto3.setId("1");
        dimensionDto3.setName("已达标");
        dimensionDto3.setValue(reached);

        DimensionDto dimensionDto4=new DimensionDto();
        dimensionDto4.setId("2");
        dimensionDto4.setName("未达标");
        dimensionDto4.setValue(unReached);
        list1.add(dimensionDto3);
        list1.add(dimensionDto4);

        resultMap.put("modelName",modelName);
        resultMap.put("percent",list);
        resultMap.put("data",list1);
        resultList.add(resultMap);
        return resultList;
    }

    public ResultDTO exportExcel(HttpServletResponse response,String fileName,Class cls,List  list) {
        try {
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1") + ".xls");
            ServletOutputStream out = response.getOutputStream();
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLS, true);
            Sheet sheet = new Sheet(1, 0, cls);
            sheet.setAutoWidth(true);
            //Sheet sheet = new Sheet(1,0,HlifeWorkExcelDto.class);
            //设置自适应宽度
            sheet.setAutoWidth(Boolean.TRUE);
            sheet.setSheetName(fileName);
            writer.write(list, sheet);
            writer.finish();
            out.flush();
            response.getOutputStream().close();
            out.close();

            // 自动列宽
            //EasyExcel.write(response.getOutputStream(), cls) .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet(fileName).doWrite(list);
            return new ResultDTO<>();
        }catch (IOException e){
            e.getMessage();
        }
        return new ResultDTO<>();
    }
}
